package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Slf4j
@Component
public class CacheClient {
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time + RandomUtil.randomLong(1, 3), unit);
    }

    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 解决缓存穿透和缓存雪崩问题
     * @param keyPrefix
     * @param id
     * @param type
     * @param dbFallback
     * @param time
     * @param unit
     * @return
     * @param <R>
     * @param <ID>
     */
    public <R, ID> R queryWithPassThrough(
            String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) {
        // 检查redis中是否存在这份店铺信息缓存
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json, type);
        }
        // 命中redis中的空值, 直接返回
        if (json != null && json.equals("")) {
            return null;
        }
        // 没有缓存, 去数据库查找, 给redis插入缓存后再返回
        R r = dbFallback.apply(id);
        if (r == null) {
            // 解决缓存穿透和缓存雪崩问题, 给redis设置空值和随机过期时间
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL + RandomUtil.randomLong(1, 3), TimeUnit.MINUTES);
            return null;
        }
        // 重建redis缓存, 随机过期时间
        this.set(key, r, time, unit);
        return r;
    }

    // 获取互斥锁
    private boolean tryLock(String key) {
        Boolean setIfAbsent = stringRedisTemplate.opsForValue().setIfAbsent(key, "1"
                , 10L, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(setIfAbsent);
    }

    // 释放互斥锁
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 互斥锁解决缓存击穿问题
     * @param keyPrefix
     * @param id
     * @param type
     * @param dbFallback
     * @param time
     * @param unit
     * @return
     * @param <R>
     * @param <ID>
     */
    public <R, ID> R queryWithMutex(
            String keyPrefix, ID id, Class<R> type, String lockPrefix, Function<ID, R> dbFallback, Long time, TimeUnit unit) {
        // 检查redis中是否存在这份店铺信息缓存
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json, type);
        }
        // 缓存穿透: 命中redis中的空值, 直接返回
        if (json != null && json.equals("")) {
            return null;
        }
        // 缓存击穿: 没命中, 需要拿到锁, 去数据库查询后重建redis缓存
        String lockKey = lockPrefix + id;
        R r = null;
        try {
            boolean getLock = tryLock(lockKey);
            if (!getLock) {
                Thread.sleep(50);
                return queryWithMutex(keyPrefix, id, type, lockPrefix, dbFallback, time, unit);
            }
            // 获取锁成功, 再次查询redis是否命中, 进行double check
            json = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(json)) {
                return JSONUtil.toBean(json, type);
            }
            // 缓存穿透: 命中redis中的空值, 直接返回
            if (json != null && json.equals("")) {
                return null;
            }
            r = dbFallback.apply(id);
            if (r == null) {
                // 缓存穿透和缓存雪崩: 给redis设置空值和随机过期时间
                stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL + RandomUtil.randomLong(1, 3), TimeUnit.MINUTES);
                return null;
            }
            // 重建redis缓存, 随机过期时间
            this.set(key, r, time, unit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unLock(lockKey);
        }
        return r;
    }

    /**
     * 逻辑过期解决商户查询的缓存击穿问题
     * @param keyPrefix
     * @param id
     * @param type
     * @param lockPrefix
     * @param dbFallback
     * @param time
     * @param unit
     * @return
     * @param <R>
     * @param <ID>
     */
    public <R, ID> R queryWithLogicalExpire(
            String keyPrefix, ID id, Class<R> type, String lockPrefix, Function<ID, R> dbFallback, Long time, TimeUnit unit) {
        // 检查redis中是否存在这份店铺信息缓存
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(json)) {
            return null;
        }
        // redis命中, 判断是否过期
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        R r = JSONUtil.toBean(data, type);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 没过期, 直接返回
        if (expireTime.isAfter(LocalDateTime.now())) {
            return r;
        }
        // 过期, 拿锁
        String lockKey = lockPrefix + id;
        boolean getLock = tryLock(lockKey);
        // 拿到锁, 开启独立线程重构redis缓存
        if (getLock) {
            // 再次检测redis缓存是否过期, 做double check
            json = stringRedisTemplate.opsForValue().get(key);
            redisData = JSONUtil.toBean(json, RedisData.class);
            data = (JSONObject) redisData.getData();
            r = JSONUtil.toBean(data, type);
            expireTime = redisData.getExpireTime();
            if (expireTime.isAfter(LocalDateTime.now())) {
                return r;
            }
            // 开启独立线程重构redis缓存
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    R newR = dbFallback.apply(id);
                    this.setWithLogicalExpire(key, newR, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(lockKey);
                }
            });
        }
        // 拿不到锁, 直接返回
        return r;
    }
}

